package com.xxxx.manager.service.impl;
import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.xxxx.common.result.RespBean;
import com.xxxx.manager.mapper.GoodsCategoryMapper;
import com.xxxx.manager.mapper.GoodsImagesMapper;
import com.xxxx.manager.mapper.GoodsMapper;
import com.xxxx.manager.pojo.Goods;
import com.xxxx.manager.pojo.GoodsCategory;
import com.xxxx.manager.service.GoodsCategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;


import java.lang.reflect.Type;
import java.util.List;

@Service
public class GoodsCategoryServiceImpl implements GoodsCategoryService {

    @Autowired
    private GoodsCategoryMapper goodsCategoryMapper;

    @Autowired
    private GoodsMapper goodsMapper;

    @Autowired
    private GoodsImagesMapper goodsImagesMapper;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Value("${goods.category.list.key}")
    private String goodsCategoryListKey;




    @Override
    public List<GoodsCategory> selectCategoryTopList() {
        return goodsCategoryMapper.selectListByParentId((short) 0);
    }

    @Override
    public List<GoodsCategory> selectListByParentId(Short id) {
        return goodsCategoryMapper.selectListByParentId(id);
    }

    /**
     * 查询级联列表
     *
     * @return
     */
    @Override
    public List<GoodsCategory> selectGoodsCategoryAll() throws Exception {
        ValueOperations<String, String> ops = redisTemplate.opsForValue();
        String gcListJson = ops.get(goodsCategoryListKey);
        //如果redis有数据，使用redis
        if (!StringUtils.isEmpty(gcListJson)){
            List<GoodsCategory> goodsCategoryList = JSON.parseArray(gcListJson,GoodsCategory.class);
            return goodsCategoryList;
        }
        List<GoodsCategory> gcList = goodsCategoryMapper.selectGoodsCategoryAll((short) 0);
        //放入Redis
        ops.set(goodsCategoryListKey,JSON.toJSONString(gcList));
        return gcList;
    }


    /**
     * 增加分类提交数据
     * @param goodsCategory
     * @return
     */
    @Override
    public RespBean insertGoodsCategory(GoodsCategory goodsCategory) {
        redisTemplate.delete(redisTemplate.keys("goods*"));
        return goodsCategoryMapper.insertGoodsCategory(goodsCategory) > 0 ? RespBean.success("success") : RespBean.error("error");
    }

    /**
     * 商品列表  新增
     * @param goods
     * @return
     */
    @Override
    public RespBean insetGoods(Goods goods) {
        if (null != goods.getGoodsId()) return RespBean.error("error");
        Integer rows = goodsMapper.insertGoods(goods);
        return rows > 0 ? RespBean.success(goods.getGoodsId().toString()) : RespBean.error("error");
    }

}


